<template>
  <div id="appStatisticPage" class="page-container">
    <div class="header-section">
      <h1 class="main-title">数据统计面板</h1>
      <p class="subtitle">实时查看应用数据分析</p>
    </div>

    <div class="statistics-card">
      <div class="card-header">
        <h2 class="card-title">热门应用统计</h2>
        <div class="card-subtitle">按回答数量统计最受欢迎的应用</div>
      </div>
      <div class="chart-container">
        <v-chart class="chart" :option="appAnswerCountOptions" />
      </div>
    </div>

    <div class="statistics-card">
      <div class="card-header">
        <h2 class="card-title">应用结果统计</h2>
        <div class="card-subtitle">查看特定应用的结果分布情况</div>
      </div>
      <div class="search-bar">
        <a-input-search
          :style="{ width: '320px' }"
          placeholder="请输入应用ID进行查询"
          button-text="查询"
          size="large"
          search-button
          @search="loadAppAnswerResultCountData"
        >
          <template #prefix>
            <icon-search />
          </template>
        </a-input-search>
      </div>
      <div class="chart-container">
        <v-chart class="chart" :option="appAnswerResultCountOptions" />
      </div>
    </div>

    <div class="statistics-card">
      <div class="card-header">
        <h2 class="card-title">应用评论统计</h2>
        <div class="card-subtitle">查看应用评论数量趋势分析</div>
      </div>
      <div class="chart-container">
        <v-chart class="chart" :option="appCommentCountOptions" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watchEffect } from "vue";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import {
  getAppAnswerCountUsingGet,
  getAppAnswerResultCountUsingGet,
  getAppCommentCountUsingGet,
} from "@/api/appStatisticController";
import VChart from "vue-echarts";
import "echarts";
import { IconSearch } from "@arco-design/web-vue/es/icon";

// 定义类型
interface AppAnswerCountDTO {
  appId: string;
  answerCount: number;
}

interface AppAnswerResultCountDTO {
  resultCount: number;
  resultName: string;
}

interface AppCommentCountDTO {
  articleId: string;
  commentCount: number;
}

// 初始化数据
const appAnswerCountList = ref<AppAnswerCountDTO[]>([]);
const appAnswerResultCountList = ref<AppAnswerResultCountDTO[]>([]);
const appCommentCountList = ref<AppCommentCountDTO[]>([]);

/**
 * 加载数据
 */
const loadAppAnswerCountData = async () => {
  try {
    const res = await getAppAnswerCountUsingGet();
    if (res.data.code === 0) {
      appAnswerCountList.value = (res.data.data || []).map(
        (item: API.AppAnswerCountDTO) => ({
          appId: String(item.appId || ""),
          answerCount: Number(item.answerCount || 0),
        })
      );
    } else {
      message.error("获取数据失败，" + res.data.message);
    }
  } catch (error) {
    message.error("网络请求失败，请稍后重试。");
  }
};

// 统计选项
const appAnswerCountOptions = computed(() => {
  return {
    color: ["#6366f1"],
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: appAnswerCountList.value.map((item) => item.appId),
      name: "应用 ID",
      axisLabel: {
        rotate: 45,
        interval: 0,
      },
    },
    yAxis: {
      type: "value",
      name: "用户答案数",
    },
    series: [
      {
        data: appAnswerCountList.value.map((item) => item.answerCount),
        type: "bar",
        barWidth: "40%",
        showBackground: true,
        backgroundStyle: {
          color: "rgba(180, 180, 180, 0.2)",
        },
        label: {
          show: true,
          position: "top",
        },
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
        },
      },
    ],
  };
});

/**
 * 加载数据
 */
const loadAppAnswerResultCountData = async (appId: string = "") => {
  if (!appId) {
    return;
  }
  try {
    const res = await getAppAnswerResultCountUsingGet({ appId: Number(appId) });
    if (res.data.code === 0) {
      appAnswerResultCountList.value = (res.data.data || []).map(
        (item: API.AppAnswerResultCountDTO) => ({
          resultCount: Number(item.resultCount || 0),
          resultName: String(item.resultName || ""),
        })
      );
    } else {
      message.error("获取数据失败，" + res.data.message);
    }
  } catch (error) {
    message.error("网络请求失败，请稍后重试。");
  }
};

// 统计选项
const appAnswerResultCountOptions = computed(() => {
  return {
    color: ["#6366f1", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6"],
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      left: "left",
      padding: 20,
      itemGap: 12,
    },
    series: [
      {
        name: "应用答案结果分布",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 8,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: "{b}: {c} ({d}%)",
        },
        emphasis: {
          label: {
            show: true,
            fontWeight: "bold",
            fontSize: 14,
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        data: appAnswerResultCountList.value.map((item) => {
          return { value: item.resultCount, name: item.resultName };
        }),
      },
    ],
  };
});

const loadAppCommentResultCountData = async () => {
  try {
    const res = await getAppCommentCountUsingGet();
    if (res.data.code === 0) {
      appCommentCountList.value = (res.data.data || []).map(
        (item: API.AppCommentCountDTO) => ({
          articleId: String(item.articleId || ""),
          commentCount: Number(item.commentCount || 0),
        })
      );
    } else {
      message.error("获取数据失败，" + res.data.message);
    }
  } catch (error) {
    message.error("网络请求失败，请稍后重试。");
  }
};

const appCommentCountOptions = computed(() => {
  return {
    color: ["#6366f1"],
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: appCommentCountList.value.map((item) => item.articleId),
      name: "应用 ID",
      axisLabel: {
        rotate: 45,
        interval: 0,
      },
    },
    yAxis: {
      type: "value",
      name: "评论数",
    },
    series: [
      {
        name: "评论数",
        data: appCommentCountList.value.map((item) => item.commentCount),
        type: "line",
        smooth: true,
        lineStyle: {
          width: 3,
          shadowColor: "rgba(0,0,0,0.3)",
          shadowBlur: 10,
          shadowOffsetY: 8,
        },
        symbol: "circle",
        symbolSize: 8,
        areaStyle: {
          opacity: 0.3,
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "#6366f1",
              },
              {
                offset: 1,
                color: "rgba(99, 102, 241, 0.1)",
              },
            ],
          },
        },
      },
    ],
  };
});

/**
 * 参数改变时触发数据的重新加载
 */
watchEffect(() => {
  loadAppAnswerCountData();
});

/**
 * 参数改变时触发数据的重新加载
 */
watchEffect(() => {
  loadAppCommentResultCountData();
});
</script>

<style scoped>
/* 页面容器样式 */
.page-container {
  padding: 32px;
  background-color: #f9fafb;
  min-height: 100vh;
  max-width: 1280px;
  margin: 0 auto;
}

/* 头部区域样式 */
.header-section {
  margin-bottom: 36px;
  text-align: center;
}

.main-title {
  font-size: 32px;
  font-weight: 700;
  color: #111827;
  margin-bottom: 12px;
  position: relative;
  display: inline-block;
}

.main-title:after {
  content: "";
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 4px;
  background: linear-gradient(90deg, #6366f1, #8b5cf6);
  border-radius: 2px;
}

.subtitle {
  font-size: 16px;
  color: #6b7280;
  margin-top: 8px;
}

/* 卡片样式 */
.statistics-card {
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  padding: 24px;
  margin-bottom: 36px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.statistics-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
}

/* 卡片头部样式 */
.card-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f3f4f6;
}

.card-title {
  font-size: 22px;
  font-weight: 600;
  color: #111827;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.card-subtitle {
  font-size: 14px;
  color: #6b7280;
}

/* 图表容器样式 */
.chart-container {
  margin-top: 20px;
  height: 380px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 搜索栏样式 */
.search-bar {
  margin-bottom: 24px;
  display: flex;
  justify-content: center;
}

/* 搜索按钮样式 */
.search-bar :deep(.arco-input-search) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-bar :deep(.arco-input-search-button) {
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  color: #fff;
  border: none;
  transition: opacity 0.3s ease;
}

.search-bar :deep(.arco-input-search-button:hover) {
  opacity: 0.9;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .main-title {
    font-size: 26px;
  }

  .card-title {
    font-size: 20px;
  }

  .chart-container {
    height: 300px;
  }
}
</style>
